var APP_VERSION = '1.01.38';

/***************** Base Object Extension *******************/

// 是否在内
function inWechat() {
	return navigator.userAgent.match(/MicroMessenger\/(\d+)\./i);
}

// 判断 是否是PC
function isPC() {
	let p = navigator.platform;
	return p.indexOf("Win") === 0 || p.indexOf("Mac") === 0;
}

// 是否android
function isAndroid() {
	var ua = navigator.userAgent;
	return ua.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
}

function isIOS() {
	var platform = navigator.platform.toLowerCase();
	var userAgent = navigator.userAgent.toLowerCase();
	return (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1 || userAgent.indexOf('mac') > -1) && (
		platform.indexOf('iphone') > -1 || platform.indexOf('ipad') > -1 || platform.indexOf('ipod') > -1 || platform.indexOf('mac') > -1);
}

// 是否在APP内
function inApp() {
	return location.pathname.indexOf('/wap') !== 0;
	// return localCache('__IN_APP__');
}

function add0(m) {
	return m < 10 ? '0' + m : m
}

function date_format(t) {
	if (!t) {
		return '0000-00-00';
	}
	//t是整数，否则要parseInt转换
	var time = new Date(t);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y + '-' + add0(m) + '-' + add0(d);
}

function datetime_format(t) {
	//t是整数，否则要parseInt转换
	var time = new Date(t);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function http_build_query(formdata, url) { // eslint-disable-line camelcase
	//  discuss at: http://locutus.io/php/http_build_query/
	// original by: Kevin van Zonneveld (http://kvz.io)
	// improved by: Legaev Andrey
	// improved by: Michael White (http://getsprink.com)
	// improved by: Kevin van Zonneveld (http://kvz.io)
	// improved by: Brett Zamir (http://brett-zamir.me)
	//  revised by: stag019
	//    input by: Dreamer
	// bugfixed by: Brett Zamir (http://brett-zamir.me)
	// bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
	//      note 1: If the value is null, key and value are skipped in the
	//      note 1: http_build_query of PHP while in locutus they are not.
	//   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;')
	//   returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
	//   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
	//   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

	var value, key, tmp = [],
		argSeparator = '&';

	var _httpBuildQueryHelper = function(key, val, argSeparator) {
		var k, tmp = [];
		if (val === true) {
			val = '1';
		} else if (val === false) {
			val = '0';
		}
		if (val !== null) {
			if (typeof val === 'object') {
				for (k in val) {
					if (val[k] !== null) {
						tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
					}
				}
				return tmp.join(argSeparator);
			} else if (typeof val !== 'function') {
				return encodeURIComponent(key) + '=' + encodeURIComponent(val);
			} else {
				throw new Error('There was an error processing for http_build_query().');
			}
		} else {
			return '';
		}
	};

	if (!argSeparator) {
		argSeparator = '&';
	}
	for (key in formdata) {
		value = formdata[key];
		var query = _httpBuildQueryHelper(key, value, argSeparator);
		if (query !== '') {
			tmp.push(query);
		}
		url = url.replace(new RegExp(key + '=[^&#]*&?', 'ig'), '');
	}

	url && (url = url.replace(/[&?]+$/, ''));
	var paramString = tmp.join(argSeparator);
	var result = !url ? '' : url + (!paramString ? '' : (url.indexOf('?') != -1 ? '&' : '?'));
	result += paramString;
	return result;
}
console.trace = function() {
	var stack = [],
		caller = arguments.callee.caller;

	while (caller) {
		caller = caller && caller.caller;
		console.log('functions on stack:' + '\n' + caller);
	}
}

function headerBarReset() {
	if (!isPlusReady()) return;
	if (window.statusBarResetDisabled) return;
	if (isHomePage()) {
		var StatusbarHeight = plus.navigator.getStatusbarHeight() || 20;
		localCache('STATUS_BAR_HEIGHT', StatusbarHeight, 30);
		$('.sctouch-home-top').css({
			'padding-top': StatusbarHeight
		});
		plus.navigator.setStatusBarStyle('light');
	} else if (isRedHeadPage() || isSharePage()) {
		plus.navigator.setStatusBarStyle('light');
	} else {
		plus.navigator.setStatusBarStyle('dark');
	}
}

// 四舍五入
Number.prototype.round = function(n) {
	var digit = Math.pow(10, n);
	return Math.round(this * digit) / digit;
};
// 进位取整
Number.prototype.ceil = function(n) {
	var digit = Math.pow(10, n);
	return Math.ceil(this * digit) / digit;
};
// 退位取整
Number.prototype.floor = function(n) {
	var digit = Math.pow(10, n);
	return Math.floor(this * digit) / digit;
}
// 去除前后空格
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, '');
}
// 字符串转化为整型
String.prototype.toInt = function() {
	var num = parseInt(this);
	return isNaN(num) ? 0 : num;
}
// 字符串转化为浮点型
String.prototype.toFloat = function() {
	var num = parseFloat(this);
	return isNaN(num) ? 0 : num;
}
// 字符串截取替换
String.prototype.strCut = function(len, replaceWith) {
	var string = this;
	return string.length > len ? string.substr(0, len - 3) + (replaceWith || '...') : string;
}
// 首字母大写
String.prototype.ucFirst = function() {
	var string = this;
	return string[0].toUpperCase() + string.substr(1);
}
// 替换全部（ 仿 php preg_replace ）
String.prototype.replaceAll = function(from, to) {
	var string = this;
	for (var i in from) {
		var regexp = new RegExp(from[i], 'g');
		string = string.replace(regexp, to[i]);
	}
	return string;
}

// 删除其中一项（,隔开）
String.prototype.remove = function(value) {
	var separator = arguments[1] || ',';
	var dataArray = this.split(separator);

	var index = dataArray.indexOf(value);
	if (index >= 0) {
		dataArray.splice(index, 1);
	}

	return dataArray.join(separator);
}

// 字符格式化
String.prototype.number_format = Number.prototype.number_format = function(decimals, decPoint, thousandsSep) {
	var number = this;
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
	var n = !isFinite(+number) ? 0 : +number
	var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
	var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
	var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
	var s = ''

	var toFixedFix = function(n, prec) {
		var k = Math.pow(10, prec)
		return '' + (Math.round(n * k) / k)
			.toFixed(prec)
	}

	// @todo: for IE parseFloat(0.55).toFixed(0) = 0;
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || ''
		s[1] += new Array(prec - s[1].length + 1).join('0')
	}

	return s.join(dec);
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) { //author: meizz
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

// 下载wgt方法
function downloadWgt(wgtUrl, label) {
	return new Promise(function(resolve, reject) {
		plus.nativeUI.showWaiting("开始下载更新 " + label + " ...");
		plus.downloader.createDownload(wgtUrl, {}, function(d, status) {
			plus.nativeUI.closeWaiting();
			if (status === 200) {
				mui.toast("下载更新包成功 " + label + ' ...');
				installWgt(d.filename, label).then(function() {
					resolve('success');
				}).catch(function(result) {
					reject(result);
				}); // 安装wgt方法
			} else {
				reject("下载更新包失败 " + label + ' ...');
			}
		}).start();
	});
}

// 安装wgt方法
function installWgt(path, label) {
	return new Promise(function(resolve, reject) {
		plus.nativeUI.showWaiting("安装更新文件 " + label + ' ...');
		plus.runtime.install(path, {}, function() {
			plus.nativeUI.closeWaiting();
			mui.toast("安装更新文件成功 " + label + ' ...');
			resolve('success');
		}, function(e) {
			plus.nativeUI.closeWaiting();
			reject("安装更新包失败[" + e.code + "]：" + e.message);
		});
	});
}

function isPlusReady() {
	return typeof plus !== 'undefined';
}

// 检查更新
function APPCheckUpdate(result) {
	if (!inApp() || isGuidePage() || !result.__upgrade__ || localCache('upgrade_lock')) return;

	if (!isPlusReady()) return;

	localCache('upgrade_lock', 1, 60 / 86400);
	// 更新提示
	mui.confirm('发现新版本，是否立即更新~', '温馨提示', ['取消', '确定'], function(res) {
		if (res.index == 0) return;

		// 升级包更新
		var process = new Promise((resolve, reject) => {
			resolve('start');
		});
		result.__upgrade__.forEach(function(item, index) {
			process = process.then(function() {
				return downloadWgt(item, (index + 1) + '/' + result.__upgrade__.length);
			});
		});
		process.then(function() {
			localCache('upgrade_lock', 0);
			mui.alert('版本更新成功', '温馨提示', '重新启动', function() {
				plus.runtime.restart();
			}, 'div');
		}).catch(function(result) {
			localCache('upgrade_lock', 0);
			mui.alert(result, '温馨提示', '重新启动', function() {
				plus.runtime.restart();
			}, 'div');
		});
	});
}


var baseApi = {};
mui.each(['get', 'post'], function(index, method) {
	baseApi[method] = function(api, data, callback, errorCallBack, completeCallback) {
		api = '/' + api.replace(/^\/|\/$/g, '');
		if (typeof data === 'function') {
			callback = data;
			data = {};
		}
		if (!callback) {
			callback = function(result) {
				mui.toast(result.result);
			}
		}
		if (!errorCallBack) {
			errorCallBack = function() {}
		}
		if (!completeCallback) {
			completeCallback = function() {}
		}

		// 如果是网络请求，走 原生
		// if(api === 'service/httpget' && typeof plus !== 'undefined') {
		//     mui.get(data.url, function (result) {
		//         // 修正接口错误
		//         result = result.replace(/:NaN/img, ':null');
		//         console.log(result);
		//         callback(JSON.parse(result));
		//         completeCallback();
		//     }, 'string');
		//     return;
		// }

		var url = http_build_query({
			key: getCookie('key'),
			_random: Math.random(),
			v: APP_VERSION
		}, ApiUrl + api);

		if (data.lock_screen) {
			// 显示加载中
			window.layerIndex = layer.open({
				type: 2,
				shadeClose: false
			});
			delete data.lock_screen;
		}

		var params = {
			url: url,
			type: method.toUpperCase(),
			data: data,
			dataType: 'json',
			beforeSend: function() {},
			error: function(jqXHR, textStatus, errorThrown) {
				// mui.toast('Network Error');
			},
			success: function(result) {
				// 显示加载中
				if (window.layerIndex === 0 || window.layerIndex > 0) layer.close(window.layerIndex || 0);

				// 版本检测
				APPCheckUpdate(result);
				if (result.code == 0 || result.code == 20000) {
					if (typeof result.login !== 'undefined' && result.login == 0) {
						delCookie('key');
						if (!checkLoginStatus()) return;
					} else {
						mui.toast(result.message);
					}
					errorCallBack(result);
				} else if (result.code == 302) {
					location.href = result.url;
				} else if (result.code == 10000) {
					return callback(result.result, result);
				} else {
					mui.toast(result.message);
				}
			},
			complete: function(result) {
				// 显示加载中
				if (window.layerIndex === 0 || window.layerIndex > 0) layer.close(window.layerIndex || 0);
				return completeCallback(result);
			}
		}
		return $.ajax(params);
	};
});

// 字符串加密
function numEnctrypt(data) {
	return Base64.encode((data * 3 + 154835) * 16);
}
// 字符串解密
function numDectrypt(data) {
	return parseInt((Base64.decode(data) / 16 - 154835) / 3);
}

// 数据字典获取
function dictGet(dict_type, callback) {
	baseApi.get('dictionary/query', {
		dict_type: dict_type
	}, function(result) {
		return callback(result);
	});
}

/**
 * 非空判断
 * 判断传入值是否为 null，undefined，“”,返回true/false
 * */
function isEmpty(value) {
	var flg = false;
	if (value == undefined || value == "" || value == null || value == "none" || value == NaN) {
		flg = true;
	}

	return flg;
}
// 获取请求参数
// name：参数名称
function getQueryString(name) {
	// 只从 url 里获取参数
	if (false && typeof plus !== 'undefined') {
		let self = plus.webview.currentWebview();
		let params = self.params;
		if (name) {
			var value = params[name];
			if (isEmpty(value)) {
				value = ""
			}
			return decodeURIComponent(value);
		} else {
			return params;
		}
	} else {
		if (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				var val = decodeURIComponent(r[2]);
				if(name == 'inviter_id' && val && /^\d+$/.test(val) === false) {
					val = numDectrypt(val);
				}
				return val;
			}
			return '';
		} else {
			let params = window.location.search.substr(1).split('&');
			var query = {};
			for (var i = 0; i < params.length; i++) {
				if (params[i]) {
					var arr = params[i].split('=');
					query[arr[0]] = decodeURIComponent(arr[1]);
				}
			}
			return query;
		}
	}
}

function addCookie(e, t, a) {
	return localCache(e, t, a);
}

// 本地缓存查询及设置
function localCache(key, data, t) {
	t = (t || 1) * (86400 * 1000); // 默认缓存1天

	key = 'DATA_CACHE_' + key;
	if (t < 0) {
		localStorage.removeItem(key);
	}
	// 取值
	else if (typeof data === 'undefined') {
		var cache = localStorage.getItem(key);
		if (cache && cache !== 'undefined') {
			cache = JSON.parse(cache);
			if (cache.expire > (new Date).getTime()) {
				return cache.data;
			}
		}
		return '';
	} else {
		var cache = {
			expire: (new Date).getTime() + t,
			data: data
		};

		cache = JSON.stringify(cache);
		localStorage.setItem(key, cache);
	}

}

function setCookie(name, value, days) {
	return localCache(name, value, days);
}

function getCookie(name) {
	if (inApp() && name === 'inviter_id') {
		// APP里面不显示邀请码
		return '';
	}
	return localCache(name);
}

function delCookie(name) {
	return localCache(name, null, -1);
}

// 关闭登录 webview
function closeWebview(pageID, duration, delay) {
	console.log('Close Page ' + pageID);
	setTimeout(function() {
		plus.webview.close(pageID, null, duration || 0);
	}, delay || 0)
}

// 关闭登录页webview
function closeLoginWebview() {
	var list = ['member/login_mobile', 'member/register_mobile', 'mall/article_show'];
	list.forEach(function(item) {
		var wb = plus.webview.getWebviewById(item);
		if (wb) {
			closeWebview(wb, 0, 0);
		}
	});
}
// 登录检测
function checkLoginStatus(callbackAction) {
	var key = getCookie('key');

	if (!key) {
		if (!callbackAction) {
			// 直接跳转去登录
			pageChange("../member/login_mobile.html");
		} else if (callbackAction === 'only_check') {
			return false;
		} else if (callbackAction === 'alert') {
			// 弹窗提示
			mui.confirm('请登录之后操作', '温馨提示', ['确定', '取消'], function(e) {
				if (e.index == 0) {
					pageChange("../member/login_mobile.html")
				}
			}, 'div');
			return false;
		}

		return false;
	} else {
		return true;
	}
}

function checkLogin(e) {
	if (e == 0) {
		//检测KEY值不正确则删除KEY值重新登录。
		delCookie('key');
		if (!checkLoginStatus()) return;
		return false
	} else {
		return true
	}
}

// 自动登录判断
function wechatAutoLoginCheck() {
	var key = getCookie('key') || '';
	var wx_logged = getQueryString('wx_logged');

	// 登录成功
	if (wx_logged) {
		key = getQueryString('key');
		loginSuccess({
			key: key,
			username: getQueryString('username')
		})
	}

	// 自动登录 || 登录绑定
	if (!key && !wx_logged) {
		if (inWechat()) {
			var inviter_id = getCookie("inviter_id");
			if (inviter_id) {
				var wxauto_login_url = ApiUrl + "/Wxauto/login.html?key=" + key + "&ref=" + encodeURIComponent(window.location.href) +
					"&inviter_id=" + inviter_id;
			} else {
				var wxauto_login_url = ApiUrl + "/Wxauto/login.html?key=" + key + "&ref=" + encodeURIComponent(window.location.href);
			}

			$.getJSON(wxauto_login_url, function(wxauto_login) {
				if (wxauto_login.code == "10000") {
					window.location.href = wxauto_login.result;
				} else {
					layer.open({
						content: wxauto_login.message,
						skin: 'msg',
						time: 2
					});
				}
			});
			return;
		} else if (isShareCPage()) {
			// 非APP内，自动注册
			baseApi.post('Mauto/register', function(result) {
				// 自动登录
				loginSuccess(result);
			});
			// let result = {
			// 	key: 'a92f0b65e8ab0154d9eba5e5c761f309',
			// 	username: 'aaaa'
			// }
			// loginSuccess(result);
			return;
		}
	}
};

// 获取用户类型
function getUserType() {
	return 1; // 暂时
	return localCache('_user_type_');
}

// 是否店主
function isInviterUser() {
	return localCache('_user_type_')
}

// 获取用户类型
function setUserType(userType) {
	return localCache('_user_type_', userType, 365);
}

// 清除本地用户信息缓存
function clearUserInfo() {
	localCache('__local_user_info__', null, -1);
}

// 获取登录用户信息
function getUserInfo(refresh = false) {
	return new Promise(function(resolve, reject) {
		let localUserInfo = localCache('__local_user_info__');
		if (!refresh && localUserInfo) {
			resolve(localUserInfo);
			return;
		}
		// 获取当前登录用户
		baseApi.get('Member/index.html', {}, function(result) {
			checkLogin(result.login);
			result.member_info.store_info = result.store_info;
			localCache('__local_user_info__', result.member_info, 1);
			resolve(result.member_info);
		});
	});
}

// 判断是否有分享名
function checkShareName() {
	return new Promise(function(resolve, reject) {
		getUserInfo().then(function(result) {
			if (!result.store_info.inviter_name) {
				if (window.checkShareNamePopup) {
					return;
				}
				// 避免重复弹出
				window.checkShareNamePopup = true;
				var layerIndex = layer.open({
					shadeClose: false,
					title: '温馨提示',
					content: '请绑定微信公众号 或 设置 分享名称，以便分享时显示您的名称！',
					btn: ['确定', '取消'],
					yes: function(index) {
						window.checkShareNamePopup = false;
						layer.close(layerIndex);
						pageChange('../member/member_information.html', {
							'class': 'inviter_share_name'
						});
					},
					no: function() {
						window.checkShareNamePopup = false;
					}
				});
			} else {
				resolve(result);
			}
		});
	})
}

// 判断是绑定账户信息
function checkAccountInfo() {
	return new Promise(function(resolve, reject) {
		baseApi.get("recharge/pd_cash_account.html", {
		}, function(result) {
			if(result.hasOwnProperty('1')) { // 支付宝账户信息
				var ali_info = result['1'];
				if(ali_info) {
					resolve(result);
					return;
				}
			}
			if(result.hasOwnProperty('3')) { // 微信账户信息
				var wx_info = result['3'];
				if(wx_info) {
					resolve(result);
					return;
				}
			}
			
			if (window.checkAccountInfoPopup) {
				return;
			}
			// 避免重复弹出
			window.checkAccountInfoPopup = true;
			var layerIndex = layer.open({
				shadeClose: false,
				title: '温馨提示',
				content: '请设置提现账户信息！',
				btn: ['确定', '取消'],
				yes: function(index) {
					window.checkAccountInfoPopup = false;
					layer.close(layerIndex);
					pageChange('../member/billing_message.html', {
					});
				},
				no: function() {
					window.checkAccountInfoPopup = false;
				}
			});
		});
	})
}

function contains(e, t) {
	var a = e.length;
	while (a--) {
		if (e[a] === t) {
			return true
		}
	}
	return false
}

function buildUrl(e, t) {
	switch (e) {
		case "keyword":
			return "../mall/product_list.html?keyword=" + encodeURIComponent(t);
		case "goods":
			return "../mall/product_detail.html?goods_id=" + t;
		case "url":
			return t
	}
	return WapSiteUrl
}

function writeClear(e) {
	if (e.val().length > 0) {
		e.parent().addClass("write")
	} else {
		e.parent().removeClass("write")
	}
	btnCheck(e.parents("form"))
}

function btnCheck(e) {
	var t = true;
	e.find("input").each(function() {
		if ($(this).hasClass("no-follow")) {
			return
		}
		if ($(this).val().length == 0) {
			t = false
		}
	});

	t = true;
	if (t) {
		e.find(".btn").parent().addClass("ok")
	} else {
		e.find(".btn").parent().removeClass("ok")
	}
}

function getSearchName() {
	var e = getQueryString("keyword");
	if (e == "") {
		if (getCookie("deft_key_value") == null) {
			$.getJSON(ApiUrl + "/Index/search_hot_info.html",
				function(e) {
					var t = e.result.hot_info;
					if (typeof t.name != "undefined") {
						$("#keyword").attr("placeholder", t.name);
						$("#keyword").html(t.name);
						addCookie("deft_key_name", t.name, 1);
						addCookie("deft_key_value", t.value, 1)
					} else {
						addCookie("deft_key_name", "", 1);
						addCookie("deft_key_value", "", 1)
					}
				})
		} else {
			$("#keyword").attr("placeholder", getCookie("deft_key_name"));
			$("#keyword").html(getCookie("deft_key_name"))
		}
	}
}

function getFreeVoucher(e) {
	var t = getCookie("key");
	if (!t) {
		checkLogin(0);
		return
	}
	$.ajax({
		type: "post",
		url: ApiUrl + "/Membervoucher/voucher_point.html",
		data: {
			vouchertemplate_id: e,
			key: t
		},
		dataType: "json",
		success: function(e) {
			checkLogin(e.login);
			var t = "领取成功";
			if (e.code != '10000') {
				t = "领取失败：" + e.message;
			}
			layer.open({
				content: t,
				skin: 'msg',
				time: 2
			});
		}
	})
}

function updateCookieCart(e) {
	var t = decodeURIComponent(getCookie("goods_cart"));
	if (t) {
		$.ajax({
			type: "post",
			url: ApiUrl + "/Membercart/cart_batchadd.html",
			data: {
				key: e,
				cartlist: t
			},
			dataType: "json",
			async: false
		});
		delCookie("goods_cart")
	}
}

function getCartCount(e, t) {
	var a = 0;
	if (getCookie("key") && !getCookie("cart_count")) {
		var e = getCookie("key");
		$.ajax({
			type: "post",
			url: ApiUrl + "/Membercart/cart_count.html",
			data: {
				key: e
			},
			dataType: "json",
			async: false,
			success: function(e) {
				if (typeof e.result.cart_count != "undefined") {
					delCookie("cart_count")
					addCookie("cart_count", e.result.cart_count, t);
					a = e.result.cart_count;
				}
			}
		})
	} else {
		a = getCookie("cart_count")
	}
	if (a > 0 && $(".sctouch-nav-menu").has(".cart").length > 0) {
		$(".sctouch-nav-menu").has(".cart").find(".cart").parents("li").find("sup").show();
		$("#header-nav").find("sup").show();
	}

	setTimeout(function() {
		if ($('#head_nav_cart').length >= 0) {
			$('#head_nav_cart span').html(a > 0 ? '<sup>' + a + '</sup>' : '');
		}
		if ($('#foot_nav_cart').length >= 0) {
			$('#foot_nav_cart').html(a > 0 ? '<sup>' + a + '</sup>' : '');
		}
	}, 100);
}

// 地址自动识别
function addressSmartParse(content, callback) {
	baseApi.post('memberaddress/address_parse', {
		content: content
	}, function(res) {
		callback(res);
	});
}

$(function() {
	$(".input-del").on('tap', function() {
		$(this).parent().removeClass("write").find("input").val("");
		btnCheck($(this).parents("form"))
	});
	$("body").on("tap", "label",
		function() {
			var thisObj = $(this);
			setTimeout(function() {
				if (thisObj.has('input[type="radio"]').length > 0) {
					thisObj.addClass("checked").siblings().removeAttr("class").find('input[type="radio"]').removeAttr("checked")
				} else if (thisObj.has('[type="checkbox"]')) {
					if (thisObj.find('input[type="checkbox"]').prop("checked")) {
						thisObj.addClass("checked")
					} else {
						thisObj.removeClass("checked")
					}
				}
			}, 100);
		});
	if ($("body").hasClass("scroller-body")) {
		new IScroll(".scroller-body", {
			mouseWheel: true,
			click: true
		})
	}
	$("#header").on("tap", "#header-nav",
		function() {
			if ($(".sctouch-nav-layout").hasClass("show")) {
				$(".sctouch-nav-layout").removeClass("show")
			} else {
				$(".sctouch-nav-layout").addClass("show")
			}
		});
	$("#header2").on("tap", "#header-nav2",
		function() {
			if ($(".sctouch-nav-layout").hasClass("show")) {
				$(".sctouch-nav-layout").removeClass("show")
			} else {
				$(".sctouch-nav-layout").addClass("show")
			}
		});
	$("#header").on("tap", ".sctouch-nav-layout",
		function() {
			$(".sctouch-nav-layout").removeClass("show")
		});
	$(document).scroll(function() {
		$(".sctouch-nav-layout").removeClass("show")
	});
	//getSearchName();
	getCartCount();
	$(document).scroll(function() {
		e()
	});
	$(".fix-block-r,footer").on("tap", ".gotop",
		function() {
			btn = $(this)[0];
			this.timer = setInterval(function() {
					$(window).scrollTop(Math.floor($(window).scrollTop() * .8));
					if ($(window).scrollTop() == 0) clearInterval(btn.timer, e)
				},
				10)
		});

	function e() {
		$(window).scrollTop() == 0 ? $("#goTopBtn").addClass("hide") : $("#goTopBtn").removeClass("hide")
	}
});
(function($) {
	$.extend($, {
		scrollTransparent: function(e) {
			var t = {
				valve: "#header",
				scrollHeight: 50
			};
			var e = $.extend({},
				t, e);

			function a() {
				$(window).scroll(function() {
					if ($(window).scrollTop() <= e.scrollHeight) {
						$(e.valve).addClass("transparent").removeClass("posf")
					} else {
						$(e.valve).addClass("posf").removeClass("transparent")
					}
				})
			}
			return this.each(function() {
				a()
			})()
		},
		dictSelected: function(options) {
			var defaults = {
				success: function(e) {}
			};
			var keyword = '';
			options = $.extend({},
				defaults, options);

			function _init() {
				if ($("#dictSelected").length > 0) {
					$("#dictSelected").remove()
				}
				var e = '<div id="dictSelected" class="slide-select input-filter-container">' +
					'<div class="sctouch-full-mask left">' + '<div class="sctouch-full-mask-bg"></div>' +
					'<div class="sctouch-full-mask-block">' + '<div class="header">' + '<div class="header-wrap">' +
					'<div class="header-l"><a ><i class="back iconfont"></i></a></div>' + '<div class="header-title">' + "<h1>" +
					options.title + "</h1>" + "</div>" + '<div class="header-r"><a ><i class="close iconfont"></i></a></div>' +
					"</div>" + "</div>" +
					'<div class="sctouch-main-layout"><div class="input-box"><input type="text" class="input-dict-filter inp" placeholder="请输入关键词搜索" /></div>' +
					'<div class="sctouch-single-nav">' + "</div>" +
					'<div class="sctouch-main-layout-a"><ul class="sctouch-default-list dict-select-options"></ul></div>' +
					"</div>" + "</div>" + "</div>" + "</div>";

				$("body").append(e);
				if (options.filter) {
					$("#dictSelected .input-box").show();
					$("#dictSelected .input-dict-filter").on('input', function() {
						keyword = $(this).val().trim();
						_getDictList();
					});
				} else {
					$("#dictSelected .input-box").hide();
				}
				_getDictList();
				_bindEvent();
				_close()
			}

			function _getDictList() {
				var html = '';
				if (keyword == '') {
					html = '<li class="text-center"><a>请输入关键词搜索</a></li>';
					$("#dictSelected").find(".sctouch-default-list").html(html).parent().scrollTop(0);
				} else {
					baseApi.get("/Dictionary/query.html", {
						dict_type: options.dict_type,
						keyword: keyword
					}, function(result) {
						html = '';
						for (var n = 0; n < result.length; n++) {
							html += '<li data-key="' + result[n].key + '" data-content="' + result[n].val + '"><a><h4>' + result[n].val +
								'</h4><span class="arrow-r"></span> </a></li>'
						}
						if (result.length == 0) {
							html = '<li class="text-center"><a>该小区尚未收录，请联系客服，微信号：18562573866。</a></li>';
						}
						$("#dictSelected").find(".sctouch-default-list").html(html).parent().scrollTop(0);
					});
				}
				return false
			}

			function _bindEvent() {
				$("#dictSelected").find(".sctouch-default-list").off("click", "li");
				$("#dictSelected").find(".sctouch-default-list").on("click", "li",
					function() {
						var key = $(this).data('key');
						if (!key) return;
						options.success({
							key: key,
							val: $(this).data('content')
						});
						$("#dictSelected").find(".sctouch-full-mask").addClass("right").removeClass("left");
					});
			}

			function _close() {
				$("#dictSelected").find(".header-l").off("click", "a");
				$("#dictSelected").find(".header-l").on("click", "a",
					function() {
						$("#dictSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
					});
				return false
			}
			return this.each(function() {
				return _init()
			})()
		},
		areaSelected: function(options) {
			var defaults = {
				success: function(e) {}
			};
			var options = $.extend({},
				defaults, options);
			var ASID = 0;
			var ASID_1 = 0;
			var ASID_2 = 0;
			var ASID_3 = 0;
			var ASNAME = "";
			var ASINFO = "";
			var ASDEEP = 1;
			var ASINIT = true;

			function _init() {
				if ($("#areaSelected").length > 0) {
					$("#areaSelected").remove()
				}
				var e = '<div id="areaSelected">' + '<div class="sctouch-full-mask left">' +
					'<div class="sctouch-full-mask-bg"></div>' + '<div class="sctouch-full-mask-block">' + '<div class="header">' +
					'<div class="header-wrap">' + '<div class="header-l"><a ><i class="back iconfont"></i></a></div>' +
					'<div class="header-title">' + "<h1>选择地区</h1>" + "</div>" +
					'<div class="header-r"><a ><i class="close iconfont"></i></a></div>' + "</div>" + "</div>" +
					'<div class="sctouch-main-layout">' + '<div class="sctouch-single-nav">' +
					'<ul id="filtrate_ul" class="area">' + '<li class="selected"><a >一级地区</a></li>' + '<li><a >二级地区</a></li>' +
					'<li><a >三级地区</a></li>' + "</ul>" + "</div>" +
					'<div class="sctouch-main-layout-a"><ul class="sctouch-default-list"></ul></div>' + "</div>" + "</div>" +
					"</div>" + "</div>";
				$("body").append(e);
				_getAreaList();
				_bindEvent();
				_close()
			}

			function _getAreaList() {
				$.ajax({
					type: "get",
					url: ApiUrl + "/Area/area_list.html",
					data: {
						area_id: ASID
					},
					dataType: "json",
					async: false,
					success: function(e) {
						if (e.result.area_list.length == 0) {
							_finish();
							return false
						}
						if (ASINIT) {
							ASINIT = false
						} else {
							ASDEEP++
						}
						$("#areaSelected").find("#filtrate_ul").find("li").eq(ASDEEP - 1).addClass("selected").siblings().removeClass(
							"selected");
						checkLogin(e.login);
						var t = e.result;
						var a = "";
						for (var n = 0; n < t.area_list.length; n++) {
							a += '<li><a data-id="' + t.area_list[n].area_id + '" data-name="' + t.area_list[n].area_name + '"><h4>' +
								t.area_list[n].area_name + '</h4><span class="arrow-r"></span> </a></li>'
						}
						$("#areaSelected").find(".sctouch-default-list").html(a).parent().scrollTop(0);

						// if (typeof myScrollArea == "undefined") {
						//     if (typeof IScroll == "undefined") {
						//         $.ajax({
						//             url: WapSiteUrl + "/js/iscroll.js?v2.0.11",
						//             dataType: "script",
						//             async: false
						//         })
						//     }
						//     myScrollArea = new IScroll("#areaSelected .sctouch-main-layout-a", {
						//         mouseWheel: true,
						//         click: true
						//     })
						// } else {
						//     myScrollArea.refresh();
						//     myScrollArea.scrollTo(0,0,0);
						// }
					}
				});
				return false
			}

			function _bindEvent() {
				$("#areaSelected").find(".sctouch-default-list").off("click", "li > a");
				$("#areaSelected").find(".sctouch-default-list").on("click", "li > a",
					function() {
						ASID = $(this).attr("data-id");
						eval("ASID_" + ASDEEP + "=$(this).attr('data-id')");
						ASNAME = $(this).attr("data-name");
						ASINFO += ASNAME + " ";
						var _li = $("#areaSelected").find("#filtrate_ul").find("li").eq(ASDEEP);
						_li.prev().find("a").attr({
							"data-id": ASID,
							"data-name": ASNAME
						}).html(ASNAME);
						if (ASDEEP == 3) {
							_finish();
							return false
						}
						_getAreaList()
					});
				$("#areaSelected").find("#filtrate_ul").off("click", "li > a");
				$("#areaSelected").find("#filtrate_ul").on("click", "li > a",
					function() {
						if ($(this).parent().index() >= $("#areaSelected").find("#filtrate_ul").find(".selected").index()) {
							return false
						}
						ASID = $(this).parent().prev().find("a").attr("data-id");
						ASNAME = $(this).parent().prev().find("a").attr("data-name");
						ASDEEP = $(this).parent().index();
						ASINFO = "";
						for (var e = 0; e < $("#areaSelected").find("#filtrate_ul").find("a").length; e++) {
							if (e < ASDEEP) {
								ASINFO += $("#areaSelected").find("#filtrate_ul").find("a").eq(e).attr("data-name") + " "
							} else {
								var t = "";
								switch (e) {
									case 0:
										t = "一级地区";
										break;
									case 1:
										t = "二级地区";
										break;
									case 2:
										t = "三级地区";
										break
								}
								$("#areaSelected").find("#filtrate_ul").find("a").eq(e).html(t)
							}
						}
						_getAreaList()
					})
			}

			function _finish() {
				var e = {
					area_id: ASID,
					area_id_1: ASID_1,
					area_id_2: ASID_2,
					area_id_3: ASID_3,
					area_name: ASNAME,
					area_info: ASINFO
				};
				options.success.call("success", e);
				if (!ASINIT) {
					$("#areaSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
				}
				return false
			}

			function _close() {
				$("#areaSelected").find(".header-l").off("click", "a");
				$("#areaSelected").find(".header-l").on("click", "a",
					function() {
						$("#areaSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
					});
				return false
			}
			return this.each(function() {
				return _init()
			})()
		},
		addressSelected: function(options) {
			var defaults = {
				success: function(e) {}
			};
			var options = $.extend({},
				defaults, options);
			var MAP = '';
			var LOCAL = '';
			var ADDRESS = "";
			var LNG = "";
			var LAT = '';

			function _init() {
				if ($("#addressSelected").length > 0) {
					$("#addressSelected").remove()
				}
				var e = '<div id="addressSelected">' + '<div class="sctouch-full-mask left">' +
					'<div class="sctouch-full-mask-bg"></div>' + '<div class="sctouch-full-mask-block">' + '<div class="header">' +
					'<div class="header-wrap">' + '<div class="header-l"><a ><i class="back iconfont"></i></a></div>' +
					'<div class="header-title">' + "<h1>选择地址</h1>" + "</div>" +
					'<div class="header-r"><a ><i class="close iconfont"></i></a></div>' + "</div>" + "</div>" +
					'<div class="map_content">' +
					'<div class="location_name"><input type="text" id="map_keywords" placeholder="小区、写字楼、学校"><span class="icon_search"></span></div>' +
					'<div id="allmap">' + "</div>" + '<div id="r-result"></div>' + "</div>" + "</div>" + "</div>" + "</div>";
				$("body").append(e);
				_getMap();
				_bindEvent();
				_close()
			}

			function _getMap() {
				MAP = new BMap.Map("allmap");
				var lng = getCookie("longitude");
				var lat = getCookie("latitude");

				if (!lng && !lat) {
					var geolocation = new BMap.Geolocation();
					geolocation.getCurrentPosition(function(r) {
						if (this.getStatus() == BMAP_STATUS_SUCCESS) {
							var lng = r.point.lng;
							var lat = r.point.lat;
							var point = new BMap.Point(lng, lat);
							MAP.centerAndZoom(point, 16);
							MAP.addControl(new BMap.NavigationControl());
							MAP.enableScrollWheelZoom();
							var marker = new BMap.Marker(point); // 创建标注
							MAP.addOverlay(marker); // 将标注添加到地图中
							marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
							//                        LNG = lng;
							//                        LAT = lat;

						} else {
							alert('failed' + this.getStatus());
						}
					}, {
						enableHighAccuracy: true
					});
				} else {
					var point = new BMap.Point(lng, lat);
					MAP.centerAndZoom(point, 16);
					MAP.addControl(new BMap.NavigationControl());
					MAP.enableScrollWheelZoom();
					var marker = new BMap.Marker(point); // 创建标注
					MAP.addOverlay(marker); // 将标注添加到地图中
					marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
				}
				MAP.addEventListener("click", function(e) {
					//                    alert(e.point.lng + ", " + e.point.lat);
					MAP.clearOverlays(); //清除标注  或者可以把market 放入数组
					var point = new BMap.Point(e.point.lng, e.point.lat);
					var marker = new BMap.Marker(point);
					MAP.addOverlay(marker);
					marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
					//
					//                    LNG = e.point.lng;
					//                    LAT = e.point.lat;
				});
				var options = {
					onSearchComplete: function(results) {
						// 判断状态是否正确
						if (LOCAL.getStatus() == BMAP_STATUS_SUCCESS) {
							var s = [];
							for (var i = 0; i < results.getCurrentNumPois(); i++) {
								s.push('<p class="address_list_wrap" data-lng="' + results.getPoi(i).point.lng + '" data-lat="' + results
									.getPoi(i).point.lat + '" data-address="' + results.getPoi(i).address + '"><span class="address_mt">' +
									results.getPoi(i).title + "</span><br><span class='address_mc'> " + results.getPoi(i).address +
									'</span></p>');
							}
							if (results.getCurrentNumPois() > 0) {

								MAP.clearOverlays(); //清除标注  或者可以把market 放入数组
								var point = new BMap.Point(results.getPoi(0).point.lng, results.getPoi(0).point.lat);
								var marker = new BMap.Marker(point);
								MAP.centerAndZoom(point, 16);
								MAP.addOverlay(marker);
								marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

								//                                            LNG = results.getPoi(0).point.lng;
								//                                            LAT = results.getPoi(0).point.lat;
								document.getElementById("r-result").innerHTML = s.join("");

							}

						}
					}
				};
				LOCAL = new BMap.LocalSearch(MAP, options);
				return false
			}

			function _bindEvent() {
				$("#addressSelected").find(".location_name").off("keyup", "#map_keywords");
				$("#addressSelected").find(".location_name").on("keyup", "#map_keywords",
					function() {
						LOCAL.search($('#map_keywords').val());
					});
				$("#addressSelected").find("#r-result").off("click", ".address_list_wrap");
				$("#addressSelected").find("#r-result").on("click", ".address_list_wrap",
					function() {
						var e = {
							address: $(this).attr('data-address'),
							lng: $(this).attr('data-lng'),
							lat: $(this).attr('data-lat')
						};
						options.success.call("success", e);
						$("#addressSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
						return false
					});
			}

			function _close() {
				$("#addressSelected").find(".header-l").off("click", "a");
				$("#addressSelected").find(".header-l").on("click", "a",
					function() {
						$("#addressSelected").find(".sctouch-full-mask").addClass("right").removeClass("left")
					});
				return false
			}
			return this.each(function() {
				return _init()
			})()
		},
		animationLeft: function(e) {
			var t = {
				valve: ".animation-left",
				wrapper: ".sctouch-full-mask",
				scroll: ""
			};
			var e = $.extend({},
				t, e);

			function a() {
				$(e.valve).click(function() {
					$(e.wrapper).removeClass("hide").removeClass("right").addClass("left");
					if (e.scroll != "") {
						if (typeof myScrollAnimationLeft == "undefined") {
							if (typeof IScroll == "undefined") {
								$.ajax({
									url: WapSiteUrl + "/js/iscroll.js?v2.0.11",
									dataType: "script",
									async: false
								})
							}
							myScrollAnimationLeft = new IScroll(e.scroll, {
								mouseWheel: true,
								click: true
							})
						} else {
							myScrollAnimationLeft.refresh()
						}
					}
				});
				$(e.wrapper).on("click", ".header-l > a",
					function() {
						$(e.wrapper).addClass("right").removeClass("left")
					})
			}
			return this.each(function() {
				a()
			})()
		},
		animationUp: function(e) {
			var t = {
				valve: ".animation-up",
				wrapper: ".sctouch-bottom-mask",
				scroll: ".sctouch-bottom-mask-rolling",
				start: function() {},
				close: function() {}
			};
			var e = $.extend({},
				t, e);

			function a() {
				e.start.call("start");
				$(e.wrapper).removeClass("down").addClass("up");
				if (e.scroll != "") {
					if (typeof myScrollAnimationUp == "undefined") {
						if (typeof IScroll == "undefined") {
							$.ajax({
								url: WapSiteUrl + "/js/iscroll.js?v2.0.11",
								dataType: "script",
								async: false
							})
						}
						myScrollAnimationUp = new IScroll(e.scroll, {
							mouseWheel: true,
							click: true
						})
					} else {
						myScrollAnimationUp.refresh()
					}
				}
			}
			return this.each(function() {
				if (e.valve != "") {
					$(e.valve).on("tap",
						function() {
							a()
						})
				} else {
					a()
				}
				$(e.wrapper).on("tap", ".sctouch-bottom-mask-bg,.sctouch-bottom-mask-close",
					function() {
						$(e.wrapper).addClass("down").removeClass("up");
						e.close.call("close")
					})
			})()
		}
	})

	$('body').on('tap', '.dict-select', function() {
		var textObj = $(this);
		var valObj = $(this).next();
		var data = $(this).data();
		data.title = $(this).attr('placeholder');
		data.success = function(item) {
			console.log(item);
			textObj.val(item.val);
			valObj.val(item.key);
		}
		$.dictSelected(data);
	});

	// 数据过滤
	$(document).on('input keyup', '.input-filter', function() {
		var keyword = $(this).val().trim();
		var reg = new RegExp(keyword);
		$($(this).data('target')).children().each(function() {
			var content = $(this).data('content');
			if (reg.test(content)) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	});
})($);
$.fn.ajaxUploadImage = function(e) {
	var t = {
		url: "",
		data: {},
		start: function() {},
		success: function() {}
	};
	var e = $.extend({},
		t, e);
	var a;

	function n() {
		if (a === null || a === undefined) {
			alert("请选择您要上传的文件！");
			return false
		}
		return true
	}
	return this.each(function() {
		$(this).on("change",
			function() {
				var t = $(this);
				e.start.call("start", t);
				let a = t.prop("files")[0];
				if (!n) return false;
				try {
					var r = new XMLHttpRequest;
					console.log(r);
					r.open("post", e.url, true);
					r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					r.onreadystatechange = function() {
						if (r.readyState == 4) {
							returnDate = $.parseJSON(r.responseText);
							e.success.call("success", t, returnDate)
						}
					};
					var i = new FormData;
					for (k in e.data) {
						i.append(k, e.data[k])
					}
					i.append(t.attr("name"), a);
					result = r.send(i)
				} catch (o) {
					mui.toast(o)
				}
			})
	})
};

function loadSeccode() {
	$("#codeimage").attr("src", ApiUrl + "/Seccode/makecode.html" + "?t=" + Math.random())
}

function favoriteGoods(e) {
	var t = getCookie("key");
	if (!t) {
		checkLogin(0);
		return
	}
	if (e <= 0) {
		layer.open({
			content: '参数错误',
			skin: 'msg',
			time: 2
		});
		return false
	}
	var a = false;
	$.ajax({
		type: "post",
		url: ApiUrl + "/Memberfavorites/favorites_add.html",
		data: {
			key: t,
			goods_id: e
		},
		dataType: "json",
		async: false,
		success: function(e) {
			if (e.code == 10000) {
				a = true
			} else {
				layer.open({
					content: e.message,
					skin: 'msg',
					time: 2
				});
			}
		}
	});
	return a
}

function dropFavoriteGoods(e) {
	var t = getCookie("key");
	if (!t) {
		checkLogin(0);
		return
	}
	if (e <= 0) {
		layer.open({
			content: '参数错误',
			skin: 'msg',
			time: 2
		});
		return false
	}
	var a = false;
	$.ajax({
		type: "post",
		url: ApiUrl + "/Memberfavorites/favorites_del.html",
		data: {
			key: t,
			fav_id: e
		},
		dataType: "json",
		async: false,
		success: function(e) {
			if (e.code == 10000) {
				a = true
			} else {
				layer.open({
					content: e.message,
					skin: 'msg',
					time: 2
				});
			}
		}
	});
	return a
}

function loadScript(url, callback) {
	var script = document.createElement("script");
	script.type = "text/javascript";
	if (typeof(callback) != "undefined") {
		if (script.readyState) {
			script.onreadystatechange = function() {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
				}
			};
		} else {
			script.onload = function() {
				callback();
			};
		}
	}
	script.src = url;
	document.body.appendChild(script);
}

function countDown(end_time) {
	var res = {};
	var endTime = new Date(end_time * 1000);
	var nowTime = new Date();
	var leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
	if (leftTime > 0) {
		res.day = leftTime ? parseInt(leftTime / (24 * 60 * 60)) : '';
		res.hour = leftTime ?
			formateTime(parseInt((leftTime / (60 * 60)) % 24)) :
			'';
		res.minute = leftTime ?
			formateTime(parseInt((leftTime / 60) % 60)) :
			'';
		res.second = leftTime ? formateTime(parseInt(leftTime % 60)) : '';
	}

	return res;
}

function formateTime(time) {
	if (time >= 10) {
		return time;
	} else {
		return '0' + time;
	}
}

/**
 * 是否是登录页
 */
function isLoginPage(page) {
	page = page || location.href;
	page += '.html';
	return /member\/login_mobile\.html/.test(page);
}
/**
 * 是否是引导页
 */
function isGuidePage(page) {
	page = page || location.href;
	page += '.html';
	return /public\/guide\.html/.test(page);
}
/**
 * 是否是购物车页面
 */
function isCartPage(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/cart_list\.html/.test(page);
}

/**
 * 是否是分享页
 */
function isSharePage(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/share\.html/.test(page);
}

/**
 * 是否是分享页
 */
function isShareCPage(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/(share_product_detail)\.html/.test(page);
}

/**
 * 是否是门店主页
 */
function isShopPortal(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/(shop_portal)\.html/.test(page);
}

/**
 * 是否是首页
 */
function isHomePage(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/index\.html/.test(page);
}

/**
 * 是否是专题页
 */
function isSpecialSalePage(page) {
	page = page || location.href;
	page += '.html';
	return /mall\/special_goods_list\.html/.test(page);
}

/**
 * 是否红色头部
 */
function isRedHeadPage(page) {
	page = page || location.href;
	page += '.html';
	return /(mall\/cart_list|member\/member|member\/balance|mall\/detection)\.html/.test(page);
}

/**
 * 是否是产品主页
 */
function isIndexPage(page) {
	page = page || location.href;
	page += '.html';
	return /(mall\/index|member\/member|member\/login_mobile|member\/login|mall\/detection)\.html/.test(page);
}

/**
 * 是否是主页
 */
function isProductDetailPage(page) {
	page = page || location.href;
	page += '.html';
	return /(mall\/product_detail)\.html/.test(page);
}

/**
 * 是否是主页
 */
function isNoNeedLoginPage(page) {
	page = page || location.href;
	page += '.html';
	return /(public\/guide|public\/order|order\/buy_step1|public\/app_download|mall\/article_show|mall\/index|mall\/product_first_categroy|search|product_list|product_detail|opening_gift_bag_list|opening_gift_bag_detail|public|member\/document|article|member\/login_mobile|member\/register_mobile|login|register|post_list)\.html/
		.test(page);
}

// 判断是否为顶部 webview
function isTopWebview(page) {
	if (typeof page !== 'object') {
		page = plus.webview.getWebviewById(page);
	}
	var topwb = getTopWindow();
	return (page.id === topwb.id);
}

// 下载
function downloadPoser() {

	var downloadTasks = [];
	var url = $('.layui-m-layer .layui-m-layercont img').attr('src');

	url = url.replace('?', '/').replace(/&/g, '/').replace(/=/g, '/') + '/_random/' + new Date().getTime()
	
	// url = http_build_query({
	// 	download: 1
	// }, url) + '&_t.png';
	plus.nativeUI.showWaiting('开始下载');
	plus.downloader.createDownload(url, {}, function(d, status) {
		plus.nativeUI.closeWaiting();
		if (status == 200) {
			plus.gallery.save(d.filename, function() { //保存到相册
				plus.io.resolveLocalFileSystemURL(d.filename, function(enpty) {
					mui.toast('保存成功');
					layer.closeAll();
				});
			}, function(e) {
				mui.alert(JSON.stringify(e));
			})
		} else {
			resolve(0);
		}
	}).start();
}
var shareDataReady = false;
window.setShareGoodsDetail = function(goods_detail) {
	getUserInfo().then(function(result) {
		window.share_goods_info = goods_detail.goods_info;
		window.share_goods_subscribe = window.share_goods_info.goods_subscribe;
		window.shareInfo = {
			"goods_id": window.share_goods_info.goods_id,
			"href": SiteDomain + '/S_' + numEnctrypt(result.member_id) + '_' + window.share_goods_info.goods_id,
			"title": window.share_goods_info.goods_name,
			"content": window.share_goods_info.goods_advword,
			"thumb": window.share_goods_info.thumb_image,
			'price': window.share_goods_info.goods_subscribe.goods_custom_price,
			"pictures": goods_detail.goods_image.split(',')
		};

		shareDataReady = true;
	});
};

// 分析链接
function shareHref(index) {
	if (!shareDataReady) {
		plus.nativeUI.showWaiting('数据加载中，请稍候...');
		window.shareReadyCallback = function() {
			plus.nativeUI.closeWaiting();
			shareHref(index);
			delete window.shareReadyCallback;
		};
		return;
	}
	getShareService(index).then(function(service) {
		var msg;
		if (index == 3 && window.shareInfo.goods_id) {
			msg = {
				thumb: window.shareInfo.pictures,
				content: '点击购买：' + window.shareInfo.href + "\r\n" + window.shareInfo.title + ',抢购价：' + window.shareInfo.price +
					'元',
			};
		} else {
			// 分享注册
			if (!window.shareInfo.goods_id) {
				window.shareInfo.thumb = window.shareInfo.thumb || 'http://www.new-seller.com/uploads/home/common/site_mobile_logo.png';
			}
			msg = {
				href: window.shareInfo.href,
				thumb: [window.shareInfo.thumb || ''],
				title: window.shareInfo.title || window.shareInfo.content,
				content: window.shareInfo.content || window.shareInfo.title,
			};
		}

		shareAction(service, msg);
	});
}

// 分享
window.shareImage = function() {
	if (!window.share_goods_subscribe) {
		mui.toast('请先认购产品');
		return;
	}
	// 获取当前登录用户
	getUserInfo().then(function(result) {
		// 弹出图片
		layer.open({
			skin: 'transparent',
			closeBtn: true,
			content: '<a class="layui-layer-ico layui-layer-close" href="javascript:;"></a>' +
				'<img width="100%" src="' + http_build_query({
					goods_id: window.share_goods_subscribe.goods_id,
					member_id: result.member_id
				}, ApiUrl + '/share/goods') + '">' +
				'<div class="share-container"><ul class="share-actions">' +
				'<li onclick="downloadPoser();">' +
				'<div class="action-icon iconfont">&#xe90a;</div><div class="action-name">保存此图片</div></li>' +
				'<li onclick="shareHref(1);">' +
				'<div class="action-icon iconfont">&#xe62d;</div><div class="action-name">微信</div></li>' +
				'<li onclick="shareHref(2);">' +
				'<div class="action-icon iconfont">&#xe900;</div><div class="action-name">QQ</div></li>' +
				'<li onclick="shareHref(3);">' +
				'<div class="action-icon iconfont">&#xe62c;</div><div class="action-name">微博</div></li></ul></div>'

				,
			area: ['10rem', '10rem']
				// , btn: ['长按保存图片去分享,点击关闭']
				//, btn: ['下载','关闭']

				,
			yes: function(index) {
				// layer.close(index);
			},
			btn2: function() {
				layer.close(index); //关闭当前窗口
			}
		});
	});
};

/**
 * 弹出分享窗口
 */
function popupShareWebview(params, check) {
	window.popupWV = getCurrentWindow();
	if (window.popupShareWV) { // 避免快速多次点击创建多个窗口
		return;
	}

	// 获取分享用户信息
	if (!checkLoginStatus()) return;

	if (params.goods_id && !check) {
		baseApi.get("goods/goods_subscribe", {
			goods_id: params.goods_id
		}, function(result) {
			if (!result) {
				mui.toast('请先认购产品');
				return;
			}

			checkShareName().then(function() {
				popupShareWebview(params, true);
			});
		});

		return;
	} else if (!check) {
		popupShareWebview(params, true);
		return;
	}

	getUserInfo().then(function(result) {
		let height = params.goods_id ? 400 : 320;
		let top = plus.display.resolutionHeight - height;
		params.inviter_id = result.member_id;
		let url = http_build_query(params, "../mall/share.html");

		let href_params = {
			inviter_id: result.inviter_id
		};
		for (let key in params) {
			if (key !== 'href' && key !== 'title' && key !== '_random') {
				href_params[key] = params[key];
			}
		}
		params.href = params.href || location.href;

		params.href = http_build_query(href_params, SiteDomain + '/wap' + params.href.replace(/^.*(\/\w+\/\w+\.html)/, '$1'));
		params.pageSourceId = window.popupWV.id;

		if(isShopPortal(params.href)) {
			// 门店主页分享
			params.href = SiteDomain + '/SP_' + result.member_id;
			params.title = params.title || (result.store_info.inviter_name + ' 的小店');
			params.content = params.content || (result.store_info.inviter_name + ' 为您推荐');
			params.thumb = result.member_avatar;
		}

		window.popupShareWV = plus.webview.create(url, "mall/share.html", {
			width: '100%',
			height: height,
			top: top,
			scrollIndicator: 'none',
			scalable: false,
			popGesture: 'none'
		}, {
			shareInfo: params
		});
		window.popupShareWV.addEventListener("loaded", function() {
			popupShareWV.show('slide-in-bottom', 300);
		}, false);
		window.popupShareWV.addEventListener("close", function() {
			closePopupShareWV();
		}, false);

		// 显示遮罩层
		window.popupWV.setStyle({
			mask: "rgba(0,0,0,0.5)"
		});
		// 点击关闭遮罩层
		window.popupWV.addEventListener("maskClick", closePopupShareWV, false);
	});

}

// 关闭分享弹窗
function closePopupShareWV() {
	window.popupWV.setStyle({
		mask: "none"
	});
	//避免出现特殊情况，确保分享页面在初始化时关闭
	if (!window.popupShareWV) {
		window.popupShareWV = plus.webview.getWebviewById("share.html" | "immediately_share.html");
	}
	if (window.popupShareWV) {
		window.popupShareWV.close();
		window.popupShareWV = null;
	}
}


//更新分享服务
function getShareService(index) {
	return new Promise(function(resolve, reject) {
		if (window.allServices) resolve(window.allServices[index]);

		plus.share.getServices(function(result) {
			var _allService = {};
			for (var key in result) {
				var service = result[key];
				_allService[service.id] = service;
			}

			window.allServices = [];
			// 更新分享列表
			var ss = _allService['weixin'];
			window.allServices.push({
				title: '',
				s: ss,
				x: 'WXSceneTimeline'
			}); // 朋友圈
			window.allServices.push({
				title: '',
				s: ss,
				x: 'WXSceneSession'
			}); // 好友
			window.allServices.push({
				title: 'QQ',
				s: _allService['qq']
			}); // ss.nativeClient 是否已安装客户端
			window.allServices.push({
				title: '新浪微博',
				s: _allService['sinaweibo']
			}); // ss.nativeClient 是否已安装客户端

			resolve(window.allServices[index]);
		}, function(e) {
			mui.toast("获取分享服务列表失败：" + e.message);
		});
	});
}

/**
 * 分享操作
 * @param {JSON} object 分享操作对象s.s为分享通道对象(plus.share.ShareService)
 */
function shareAction(object, msg) {
	if (!object || !object.s) {
		console.log("无效的分享服务！");
		return;
	}
	if (!object.s.nativeClient) {
		console.log("请先安装 " + object.title + " APP！");
		return;
	}
	plusSendShare(object, msg);
}

/**
 * 发送分享消息
 * @param {plus.share.ShareService} object
 * @param {JSON} msg
 */
function plusSendShare(object, msg) {
	var service = object.s;
	msg.extra = {
		scene: object.x
	};

	plus.nativeUI.showWaiting();

	var downloadTasks = [];
	msg.pictures = [];
	// 图片下载
	msg.thumb.forEach(function(item) {
		// 下载开始
		downloadTasks.push(new Promise(function(resolve, reject) {
			var imgDtask = plus.downloader.createDownload(item, {
				method: 'GET'
			}, function(d, status) {
				console.log(d.filename);
				if (status == 200) {
					msg.pictures.push(d.filename);
					resolve(1);
				} else {
					resolve(0);
				}
			});
			imgDtask.start();
		}));

	});
	// 下载任务捕获
	Promise.all(downloadTasks).then(function(result) {
		plus.nativeUI.closeWaiting();

		msg.thumbs = msg.pictures;
		// 发送分享
		if (service.authenticated) {
			console.log("---已授权---");
			_plusSendShare(msg, service);
		} else {
			console.log("---未授权---");
			service.authorize(function() {
				_plusSendShare(msg, service);
			}, function(e) {
				mui.toast("认证授权失败：" + e.code + " - " + e.message);
			});
		}
	});
}

// 分享
function _plusSendShare(msg, service) {
	console.log(JSON.stringify(msg));
	service.send(msg, function() {
		// baseApi.method
		if (!goods_id) return;

		// 分享成功关闭分享
		closeCurrentWindow();
		baseApi.post("/Goods/share", {
				goods_id: goods_id,
				time_goods_id: time_goods_id,
			},
			function(e) {})
	}, function(e) {
		if (e.code == -2) {
			mui.toast('取消分享');
		} else {
			mui.toast(e.message);
		}
	});
}

// 原生复制
function plusCopy(copy_content, msg) {
	msg = msg || "复制成功";
	//判断设备是android还是ios
	if(mui.os.ios){ //ios
		var UIPasteboard = plus.ios.importClass("UIPasteboard");
		var generalPasteboard = UIPasteboard.generalPasteboard();
		//设置/获取文本内容:
		generalPasteboard.plusCallMethod({
			setValue:copy_content,
			forPasteboardType: "public.utf8-plain-text"
		});
		generalPasteboard.plusCallMethod({
			valueForPasteboardType: "public.utf8-plain-text"
		});
		mui.toast(msg);  //自动消失提示框
	}else{  //android
		var context = plus.android.importClass("android.content.Context");
		var main = plus.android.runtimeMainActivity();
		var clip = main.getSystemService(context.CLIPBOARD_SERVICE);
		plus.android.invoke(clip,"setText",copy_content);
		mui.toast(msg);  //自动消失提示框
	}
};

/// 打开微信
function openWechat() {
	location.href = 'weixin://';
}


function resetPageChangeParamSign() {
	pageChangeParamSign = null;
}

// 页面跳转
// url：页面url
// params：目标页面参数
// backend：是否是后台加载
var pageChangeParamSign = '';

function pageChange(url, params, backend) {
	// pagechange 之后不允许重置任务栏
	window.statusBarResetDisabled = true;

	var sign = url + JSON.stringify(params);
	// 避免重复提交
	if (sign === pageChangeParamSign) return;

	params = params || {};
	var pageID = url.replace(/^.*\/((\w+)\/(\w+))\.html.*$/, '$1');
	// 记录登录前的页面
	if (pageID === 'member/login_mobile') {
		if (inWechat()) {
			logoutSuccess(); // 清除登录状态
			wechatAutoLoginCheck();
			return;
		}
		localCache('login_prev_page', {
			page_id: location.href.replace(/^.*\/([^\/]+\/[^\/]+)\.html.*$/, '$1'),
			params: getQueryString()
		});
	}
	if (isPlusReady() && /^http/.test(url)) {
		return pageChange('../mall/exlink.html', {
			url: url,
			back_close: params.back_close || '',
			title: params.title || '站外链接',
			full_screen: params.full_screen || ''
		}, false);
	}
	// 正式环境去除 js 跳转
	if (!inWechat() && !isPC() && !isShareCPage() && !isPlusReady()) {
		setTimeout(function() {
			pageChange(url, params, backend);
		}, 100);
		return;
	}

	var t = this;
	params._random = Math.random();

	if (!url) return; // 链接为空

	if (isSharePage(url)) {
		return popupShareWebview(params);
	}

	url = http_build_query(params, url);

	if (typeof plus === 'undefined' || isShareCPage()) {
		location.href = url;
	} else {
		// 如果是主页，直接显示
		var aniShow = 'slide-in-right';
		if (!isLoginPage(location.href) && isIndexPage(url)) {
			// aniShow = 'none';
		}

		// 如果是主页，刷新页面
		var wb = plus.webview.getWebviewById(pageID) || '';

		if (wb && !isProductDetailPage(pageID)) {
			// 检查地址是否正确
			if ((new RegExp(pageID)).test(wb.getURL())) {} else {
				wb.loadURL(url);
			}
			aniShow = 'none';
			plus.webview.show(pageID, aniShow, 300, function() {
				wb.evalJS('pageReload(' + JSON.stringify(params) + ');');
				wb.evalJS('pageReShow(' + JSON.stringify(params) + ');');
				resetPageChangeParamSign();
			});
			return;
		} else if (wb) {
			// 打开新页面，关闭旧页面
			closeWebview(wb, 0, 1000);
		}

		let style = {
			statusbar: {
				background: "#F2F2F2"
			}, //WebviewStatusbarStyles类型,窗口状态栏样式.仅在应用设置为沉浸式状态栏样式下有效,设置此属性后将自动保留系统状态栏区域不被Webview窗口占用(即Webview窗口非沉浸式样式显示).
		};

		//判断不是首页改变导航栏的背景和字体颜色
		if (isHomePage(url)) {
			style = {};
		} else if (isRedHeadPage(url)) {
			style = {
				statusbar: {
					background: "#FF3323"
				} //WebviewStatusbarStyles类型,窗口状态栏样式.仅在应用设置为沉浸式状态栏样式下有效,设置此属性后将自动保留系统状态栏区域不被Webview窗口占用(即Webview窗口非沉浸式样式显示).
			}
		}

		// var nw = mui.openWindow({
		// 	id: pageID,
		// 	url: url,
		// 	show: {
		// 		autoShow: !backend, //页面loaded事件发生后自动显示，默认为true
		// 		aniShow: aniShow, //页面显示动画，默认为”slide-in-right“；
		// 		duration: 300 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
		// 	},
		// 	styles: style,
		// 	createNew: true,
		// 	waiting: {
		// 		autoShow: false
		// 	},
		// 	extras: {
		// 		params: params
		// 	}
		// });
		var nw = plus.webview.create(url, pageID, style, {
			params: params
		});
		nw.addEventListener("loaded", function() {
			nw.show('slide-in-right', 300);
		}, false);
		
        window.newPageWindowListen = function() {
	        nw.addEventListener('close', function(e){
		        window.statusBarResetDisabled = false;
		        // 改变 statusbar 颜色，背景颜色
		        headerBarReset();
		        // 上级页面数据重新加载
		        window.pageReload();
	        }, false);
	        nw.addEventListener('show', function(e){
		        // 页面显示 改变 statusbar 颜色，背景颜色
		        nw.evalJS('headerBarReset();');
		        resetPageChangeParamSign();
	        }, false);
        }
    }
};

// 判断当前webview 是否在最顶部
function currentIsTopWindow() {
	return isTopWebview(getCurrentWindow());
}

// 当前页面
function getCurrentWindow() {
	return plus.webview.currentWebview();
}

// 父级页面
function getOpennerWindow() {
	return plus.webview.currentWebview().opener();
}

// 当前页面
function getTopWindow() {
	let all = plus.webview.all();
	return all.pop();
}
// 关闭当前页面
function closeCurrentWindow() {
	if (isPlusReady()) {
		var currentWebview = plus.webview.currentWebview();
		currentWebview.close('slide-out-right', 300);
	} else {
		history.back();
	}
}
// 关闭所有页面
function clearAllWindows() {
	var all = plus.webview.all();

	for (let key in all) {
		if (all[key] !== plus.webview.currentWebview()) {
			plus.webview.close(all[key]);
		}
	}
}

// 获取系统
function getClientType() {
	if (isPlusReady()) {
		if (mui.os.ios) return 'ios';
		if (mui.os.android) return 'android';
	} else {
		return 'wap';
	}
}

// 获取认购弹出层
function goodsSubscribeLayerShow(goods_detail) {
	window.popupSubscribeGoodsDetail = goods_detail;
	var goodsSubscribeLayer = $('#product_subscribe_html');
	if (goodsSubscribeLayer.length === 0) {
		var html = '<div id="product_subscribe_html" class="sctouch-bottom-mask">\n' +
			'    <div class="sctouch-bottom-mask-bg"></div>\n' +
			'    <div class="sctouch-bottom-mask-block">\n' +
			'        <div class="sctouch-bottom-mask-top goods-options-info">\n' +
			'            <div class="goods-pic">\n' +
			'                <img class="goods-image" src="">\n' +
			'            </div>\n' +
			'            <dl>\n' +
			'                <dd class="goods-price">\n' +
			'                    ￥<em class="price">1110.00</em>\n' +
			'                </dd>\n' +
			'                <dt class="goods-name"></dt>\n' +
			'                <!--拼团相关单独显示,不和 限时折扣和抢购归为一类-->\n' +
			'\n' +
			'            </dl>\n' +
			'            <a class="sctouch-bottom-mask-close"><i></i></a>\n' +
			'        </div>\n' +
			'        <div class="goods-option-value">' +
			'           <div class="option-item">销售价\n' +
			'            <div class="value-box">\n' +
			'                <span class="price-set">\n' +
			'                   <input type="text" class="custom-price input-float" value="" placeholder="请填写合适的销售价格">\n' +
			'               </span>' +
			'               <div class="price-calc">' +
			'                   <div class="market-price">市场价￥<span class="price-value"></span></div>' +
			'                   <div class="goods-profit">赚 <span class="price-value">??</span> 元 (扣除运/税费)</div>' +
			'               </div>\n' +
			'            </div>\n' +
			'            <div class="bbc-notice mui-hidden">温馨提醒：该商品为跨境商品，综合税率为 <span class="tax-rate"></span>，会在您的销售价中扣除，税金计算方式为：销售价*<span class="tax-rate"></span></div>' +
			'            </div>\n' +
			'           <div class="option-item">价格力\n' +
			'            <div class="value-box">\n' +
			'                <span class="price-grade" data-value="弱↓">弱↓</span>\n' +
			'                <span class="price-grade" data-value="一般">一般</span>\n' +
			'                <span class="price-grade" data-value="强↑">强↑</span>\n' +
			'                <span class="price-grade" data-value="很强↑↑">很强↑↑</span>\n' +
			'                <span class="price-grade" data-value="异常">异常</span>\n' +
			'            </div>\n' +
			'            </div>\n' +
			'        </div>\n' +
			'<div class="form-btn ok goods-subscribe-save"><a class="btn">确认</a></div>' +
			'    </div>\n' +
			'</div>';
		goodsSubscribeLayer = $(html);
		goodsSubscribeLayer.appendTo('body');
	}

	// 隐藏
	if (typeof goods_detail === 'boolean') {
		if (goods_detail) {
			goodsSubscribeLayer.removeClass('down').addClass('up');
		} else {
			goodsSubscribeLayer.removeClass('up').addClass('down');
		}
		return;
	}

	var goods_info = goods_detail.goods_info;

	goodsSubscribeLayer.find('.goods-name').text(goods_info.goods_name);
	goodsSubscribeLayer.find('.goods-image').attr('src', goods_info.thumb_image);
	goodsSubscribeLayer.find('.goods-price .price').text(goods_info.time_goods.goods_price);
	if (goods_info.is_fixed_price != 1) {
		window.defaultCustomPrice = goods_info.goods_subscribe ? 0 : goods_info.goods_marketprice;
		goodsSubscribeLayer.find('.custom-price').val(goods_info.goods_subscribe ? goods_info.goods_subscribe.goods_custom_price : goods_info.goods_marketprice).prop('readonly', false);
	} else {
		// 限价，只能以市场价认购
		goodsSubscribeLayer.find('.custom-price').val(goods_info.goods_marketprice).prop('readonly', true);

		var goodsProfit = (goods_info.goods_marketprice - goods_info.time_goods.goods_price).number_format(2);
		if (goods_info.goods_subscribe) {
			layer.open({
				title: [
					'限价商品认购提醒',
					'background-color: #FF4351; color:#fff;'
				],
				content: '商品已认购！销售价 ' + goods_info.goods_marketprice + '，您可赚 <span style="color: #FF4351;">' + goods_info.goods_subscribe.goods_commission +
					'</span>',
				time: 4
			});
			return;
		} else {
			baseApi.post("/membersubscribe/save.html", {
				goods_id: goods_info.goods_id,
				price: goods_info.goods_marketprice
			}, function(msg, result) {
				var goodsSubscribe = $('.goods-subscribe[data-goods_id="' + goods_info.goods_id + '"]');
				goodsSubscribe.addClass('favorate').show();
				goodsSubscribe.find('.custom-price-profit').text(goodsProfit);
				goodsSubscribe.find('.desc').text('已认购');
				$('.site-subscribe[data-goods_id="' + goods_info.goods_id + '"]').hide();
				window.goods_subscribe = true;
				setTimeout(function() {
					layer.open({
						title: [
							'限价商品认购提醒',
							'background-color: #FF4351; color:#fff;'
						],
						content: '认购成功！销售价 ' + result.goods_custom_price + '，扣除运费/税费，您可赚 <span style="color: #FF4351;">' + result.goods_commission +
							'</span>',
						time: 4
					});
				}, 300);
			}, function(result) {});
			return;
		}
	}
	goodsSubscribeLayer.find('.price-calc .market-price .price-value').text(goods_info.goods_marketprice);
	goodsSubscribeLayer.find('.price-calc .goods-profit .price-value').text(goods_info.goods_subscribe ? goods_info.goods_subscribe.goods_commission : '??');
	goodsSubscribeLayer.find('.price-grade').removeClass('active');
	var currentGrade = goodsSubscribeLayer.find('.price-grade[data-value="' + (goods_info.goods_subscribe ? goods_info.goods_subscribe.goods_price_grade : '') + '"]');
	if (currentGrade.length > 0) {
		currentGrade.addClass('active');
	}

	goodsSubscribeLayer.find('.custom-price').change();

	goodsSubscribeLayer.removeClass('down').addClass('up');
}

// 记录搜索关键词
function addSearchHistory(keyword) {
	var history = getCookie('__his_search__') || [];
	var list = [];
	list.push(keyword);
	history.forEach(function(item) {
		if (list.indexOf(item) >= 0) return;
		list.push(item);
	});
	setCookie('__his_search__', list, 365);
}

// 获取搜索记录
function getSearchHistory() {
	return getCookie('__his_search__') || [];
}

// 加入购物车
function addToCart(goods_id, time_goods_id, callback) {
	if (!checkLoginStatus()) return;
	baseApi.post("/Membercart/cart_add", {
			goods_id: goods_id,
			time_goods_id: time_goods_id,
			quantity: 1
		},
		function(e) {
			mui.toast('添加成功');
			delCookie("cart_count");
			getCartCount();

			// 购物车页面更新
			if (isCartPage()) {
				pageReload();
			}

			callback();
		})
}

//复制内容
function copyToClip(text, notice, callback) {
	var copyInput = $('#copy-input');
	if (copyInput.length == 0) {
		copyInput = $(
			'<input id="copy-input" type="text" value="ss" style="position: fixed;left: -20rem;" readonly ="readonly"/>').appendTo(
			'body');
	}
	copyInput.val(text);

	let input = document.getElementById('copy-input');
	input.select();
	document.execCommand('copy', false);
	mui.toast(notice || "复制成功");
	if (callback) window[callback]();
}

function photoSwipePopup(images, index) {
	let imgList = [];

	images.each(function() {
		let config = {
			src: $(this).attr('data-image_url'), // 原图地址
			w: $(this).attr('data-w') || 100, // 图片宽度
			h: $(this).attr('data-h') || 100, // 图片高度
		}
		imgList.push(config);
	});
	index = index || 0;
	var pswpElement = document.querySelectorAll('.pswp')[0];

	// build items array
	// define options (if needed)
	var options = {
		// optionName: 'option value'
		// for example:
		index: index // start at first slide
	};

	// Initializes and opens PhotoSwipe
	var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, imgList, options);
	gallery.listen('imageLoadComplete', function(index, item) {
		setTimeout(function() {
			if (!item.container || images.eq(index).attr('data-w')) return;
			let img = item.container.children[1];
			if (!img) return;
			item.w = img.naturalWidth;
			item.h = img.naturalHeight;
			gallery.invalidateCurrItems();
			gallery.updateSize(true);

			images.eq(index).attr('data-w', img.naturalWidth);
			images.eq(index).attr('data-h', img.naturalHeight);
		}, 1000)
	});
	gallery.init();
}

// 加载图片插件
function loadPhotoSwipe() {
	let task = [];
	task.push(new Promise(function(resolve, reject) {
		/*JavaScript动态加载Js文件*/
		let scriptNode = document.createElement('script');
		scriptNode.src = '../js/photoswipe/photoswipe.js?v2.0.11'; /*附带时间参数，防止缓存*/
		scriptNode.onload = function() {
			resolve(1);
		}
		document.head.appendChild(scriptNode);
	}));
	task.push(new Promise(function(resolve, reject) {
		/*JavaScript动态加载Js文件*/
		let scriptNode = document.createElement('script');
		scriptNode.src = '../js/photoswipe/photoswipe-ui-default.js?v2.0.11'; /*附带时间参数，防止缓存*/
		scriptNode.onload = function() {
			resolve(1);
		}
		document.head.appendChild(scriptNode);
	}));
	task.push(new Promise(function(resolve, reject) {
		var html = '\n' +
			'    <!--必要样式-->\n' +
			'    <!-- Core CSS file -->\n' +
			'    <link rel="stylesheet" href="../js/photoswipe/photoswipe.css?v2.0.11">\n' +
			'\n' +
			'    <!-- Skin CSS file (styling of UI - buttons, caption, etc.)\n' +
			'         In the folder of skin CSS file there are also:\n' +
			'         - .png and .svg icons sprite,\n' +
			'         - preloader.gif (for browsers that do not support CSS animations) -->\n' +
			'    <link rel="stylesheet" href="../js/photoswipe/default-skin/default-skin.css?v2.0.11">\n' +
			'<!-- Root element of PhotoSwipe. Must have class pswp. -->\n' +
			'<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">\n' +
			'\n' +
			'    <!-- Background of PhotoSwipe.\n' +
			'         It\'s a separate element as animating opacity is faster than rgba(). -->\n' +
			'    <div class="pswp__bg"></div>\n' +
			'\n' +
			'    <!-- Slides wrapper with overflow:hidden. -->\n' +
			'    <div class="pswp__scroll-wrap">\n' +
			'\n' +
			'        <!-- Container that holds slides.\n' +
			'            PhotoSwipe keeps only 3 of them in the DOM to save memory.\n' +
			'            Don\'t modify these 3 pswp__item elements, data is added later on. -->\n' +
			'        <div class="pswp__container">\n' +
			'            <div class="pswp__item"></div>\n' +
			'            <div class="pswp__item"></div>\n' +
			'            <div class="pswp__item"></div>\n' +
			'        </div>\n' +
			'\n' +
			'        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->\n' +
			'        <div class="pswp__ui pswp__ui--hidden">\n' +
			'\n' +
			'            <div class="pswp__top-bar">\n' +
			'\n' +
			'                <!--  Controls are self-explanatory. Order can be changed. -->\n' +
			'\n' +
			'                <div class="pswp__counter"></div>\n' +
			'\n' +
			'                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>\n' +
			'\n' +
			'                <!--<button class="pswp__button pswp__button&#45;&#45;share" title="Share"></button>-->\n' +
			'\n' +
			'                <!--<button class="pswp__button pswp__button&#45;&#45;fs" title="Toggle fullscreen"></button>-->\n' +
			'\n' +
			'                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>\n' +
			'\n' +
			'                <!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->\n' +
			'                <!-- element will get class pswp__preloader--active when preloader is running -->\n' +
			'                <div class="pswp__preloader">\n' +
			'                    <div class="pswp__preloader__icn">\n' +
			'                        <div class="pswp__preloader__cut">\n' +
			'                            <div class="pswp__preloader__donut"></div>\n' +
			'                        </div>\n' +
			'                    </div>\n' +
			'                </div>\n' +
			'            </div>\n' +
			'\n' +
			'            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">\n' +
			'                <div class="pswp__share-tooltip"></div>\n' +
			'            </div>\n' +
			'\n' +
			'            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">\n' +
			'            </button>\n' +
			'\n' +
			'            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">\n' +
			'            </button>\n' +
			'\n' +
			'            <div class="pswp__caption">\n' +
			'                <div class="pswp__caption__center"></div>\n' +
			'            </div>\n' +
			'\n' +
			'        </div>\n' +
			'\n' +
			'    </div>\n' +
			'\n' +
			'</div>';

		$('body').append(html);
		resolve(1);
	}));
	return Promise.all(task);
}


// 微信登录
function wxLoginFn(callback) {
	let self = this;

	if(!plus.runtime.isApplicationExist({pname:'com.tencent.mm',action:'weixin://'})){
		layer.close(window.layerIndex);
		mui.toast("微信应用未安装,请安装后尝试！");
		return;
	}

	// 微信授权登录对象
	let aweixin = null;
	// 当前环境支持的所有授权登录对象
	let auths = null;

	// 获取登录授权认证服务列表，单独保存微信登录授权对象
	function getService() {
		plus.oauth.getServices(function(services) {
			layer.close(layerIndex);
			auths = services;
			authLogin()
		}, function(e) {
			layer.close(window.layerIndex);
			plus.nativeUI.alert("获取登录授权服务列表失败，请稍后重试");
			// plus.nativeUI.alert("获取登录授权服务列表失败："+JSON.stringify(e));
		});
	}

	// 获取微信登录授权对象后可进行登录认证操作
	function authLogin() {
		for (let i = 0; i < auths.length; i++) {
			if (auths[i].id == 'weixin') {
				aweixin = auths[i];
				break;
			}
		}
		if (!aweixin) {
			layer.close(layerIndex);
			plus.nativeUI.alert("当前环境不支持微信登录");
			return;
		}

		if (!aweixin) {
			layer.close(layerIndex);
			plus.nativeUI.alert("当前环境不支持微信登录");
			return;
		}

		aweixin.login(function(e) {
			layer.close(layerIndex);
			authUserInfo(e);
		}, function(e) {
			aweixin.login(function(e) {
				authUserInfo(e);
			}, function(e) {
				layer.close(window.layerIndex);
			});
		});
	}

	// 获取微信登录授权对象后获取用户信息操作
	function authUserInfo() {
		if (!aweixin) {
			layer.close(layerIndex);
			plus.nativeUI.alert("当前环境不支持微信登录");
			return;
		}
		window.layerIndex = layer.open({
			shadeClose: false,
			type: 2
		});

		if (aweixin.authResult) {
			aweixin.getUserInfo(function(e) {
				//登录成功处理
				layer.close(window.layerIndex);
				let wxUserInfo = aweixin.userInfo;
				authLoginOut(); //注销登录防止切换账号获取到旧信息
				callback(wxUserInfo);
			}, function(e) {
				console.log("获取用户信息失败： " + JSON.stringify(e));
			});
		} else {
			layer.close(window.layerIndex);
			plus.nativeUI.alert("未登录认证!");
		}
	}

	// 注销登录认证
	function authLoginOut() {
		aweixin.logout(function(e) {
			// plus.nativeUI.alert("注销登录认证成功!"+JSON.stringify(e));
		}, function(e) {
			console.log("注销登录认证失败!");
		});
	}

	getService();
}

// 地址显示字段
function changeTradeMode() {
	$('.address-custom-notice').hide();
	$('.trade_mode-3, .trade_mode-2').hide();

	$('#real_name, #id_card_no').prop('readonly', false);

	$('.trade_mode-' + trade_mode).show();
	if (trade_mode == 2) {
		$('.address-custom-notice').text('提示：根据海关要求，需要提供订购人身份信息，并完成实名认证；');
		$('.address-custom-notice').show();

		baseApi.get('memberaddress/real_name_address', {}, function(res) {
			if (res && res.real_name) {
				// 实名信息
				$('#real_name, #id_card_no').prop('readonly', true);
				$('#real_name').val(res.real_name);
				$('#id_card_no').val(res.id_card_no);
			}
		});
	} else if (trade_mode == 3) {
		$('.address-custom-notice').text('提示：根据海关要求，所有海外直邮商品均需要客户上传收件人身份证影印件；');
		$('.address-custom-notice').show();
	}

}

// 登录成功
function loginSuccess(userInfo) {
	clearUserInfo();
	setCookie('key', userInfo.key, 10 * 365); // 10年
	setCookie('username', userInfo.username, 10 * 365); // 10年
}

function logoutSuccess() {
	delCookie("username");
	delCookie("key");
	setUserType('');
}

// 登录成功
function loginSuccessCallback() {
	var loginPrevPage = localCache('login_prev_page');

	if (!isPlusReady() && loginPrevPage) {

		closeCurrentWindow();
		// pageChange('../' + loginPrevPage.page_id + '.html', loginPrevPage.params);
	} else {
		pageChange("../member/member.html");
	}

	localCache('login_prev_page', null, -1);
	localCache('reg_wxinfo', null, -1);

	setTimeout(function() {
		// 关闭登录页
		closeLoginWebview();
	}, 1000);
}

// 检查本地图片缓存，超过5分钟的图片进行清理
function clearTimeOutImage() {
	//本地下载图片缓存
	var local_img_cache = localCache('__IMG_LOCAL_CACHE__');
	
	if (false && !local_img_cache) {
		return;
	} else {
		// 删除下载所有文件
		plus.io.resolveLocalFileSystemURL('_downloads/', function(entry) {
			// 可通过entry对象操作test.html文件 
			entry.remove( function(entry ){
				plus.console.log( "Remove succeeded" );
			});
			entry.removeRecursively( function ( entry ) {
				plus.console.log( "Remove Recursively Succeeded" );
			});
		}, function ( e ) {
		});
			
		localCache('__IMG_LOCAL_CACHE__',false)
	}
}

/************************** 页面初始化 事件监听 及 检测 Start ****************************/

(function() {
	// 如果已经登录，查询用户类型
	let userType = getUserType();
	if (!userType && getCookie('key')) {
		getUserInfo().then(function(result) {
			setUserType(result.store_info && result.store_info.inviter_state == 1 ? 1 : '');
		})
	}

	// 邀请人记录
	if (getQueryString("inviter_id")) {
		inviter_id = getQueryString("inviter_id");
		//计入cookie
		setCookie('inviter_id', inviter_id, 1);
	}

	// 自动登录
	if (getQueryString('auto_login')) {
		loginSuccess({
			key: getQueryString('key'),
			username: getQueryString('username')
		})
	}

	// 判断登录页判断
	if (!isNoNeedLoginPage()) {
		if (!getCookie('key')) {
			pageChange('../member/login_mobile.html');
		}
	}

	/************* PAGE listen start **************/

	// mui全局处理
	mui.init({
		// beforeback: function() {
		// 	// 页面回调方法
		// 	if (typeof beforeback === 'function') {
		// 		beforeback.call();
		// 	}
		// },
		keyEventBind: {
			backbutton: true //开启back按键监听
		}
	});

	// 页面数据重新加载
	window.pageReload = function() {};
	window.pageReShow = function() {};
	window.newPageWindowListen = function() {};
	// plus ready
	mui.plusReady(function() {
		localCache('__IN_APP__', true);
		// 记录用户设备信息
		var deviceInfo = plus.push.getClientInfo();
	    // 页面显示 改变 statusbar 颜色，背景颜色
	    headerBarReset();
	    resetPageChangeParamSign();

	    var opener = getOpennerWindow();
		if(opener) opener.evalJS('window.newPageWindowListen()');
		clearTimeOutImage();

		// 存储设备信息
		if (APP_DEBUG || (!localCache('DEVICE_ID_SAVED') && getCookie('key'))) {
			baseApi.post(
				'device/log', {
					device_info: deviceInfo
				},
				function(result) {
					if (result === 'success') {
						localCache('DEVICE_ID_SAVED', 1, 1);
					}
				}
			);
		}

		// 两次点击退出
		(function() {
			var tuichu = "再按一次退出程序";
			var backButtonPress = 0;

			mui.back = function(event) {
				if (isIndexPage()) {
					// 首页两次退出
					backButtonPress++;
					if (backButtonPress > 1) {
						var main = plus.android.runtimeMainActivity();
						main.moveTaskToBack(false);
						// 关闭所有无用窗口
						clearAllWindows();
						return false;
					} else {
						plus.nativeUI.toast(tuichu);
					}
					setTimeout(function() {
						backButtonPress = 0;
					}, 1000);
					return false;
				} else {
					// 关闭当前 webwiew
					closeCurrentWindow();
				}
			};
		}());
	});

	function pickerLoad() {
		return window.pickerObj = window.pickerObj || new mui.PopPicker();
	}

	// 多选
	$('body').on('tap', '.checkbox-wrap', function() {
		var pickerPlaceholder = $(this).find('.check-placeholder');
		var optionsObj = $(this).find('option');
		var picker = pickerLoad();
		var options = [];
		optionsObj.each(function() {
			options.push({
				value: $(this).val(),
				text: $(this).text(),
				obj: $(this)
			});
		});

		// 选择
		picker.setData(options);
		picker.show(function(selectItems) {
			if (selectItems[0].obj.prop('selected')) return; // 已选择的
			var selectItem = $('<span class="checked-item" data-value="' + selectItems[0].value + '">' + selectItems[0].text +
				'<i class="remove iconfont">&#xe683;</i></span>');
			pickerPlaceholder.before(selectItem);
			selectItems[0].obj.prop('selected', true);

			// 多选删除
			selectItem.find('.remove').on('tap', function() {
				var item = $(this).parents('.checked-item');
				var val = item.data('value');
				$(this).parents('.checkbox-wrap').find('option[value="' + val + '"]').prop('selected', false);
				item.remove();
				return false;
			});
		});
	});

	// 下拉
	$('body').on('tap', '.select-wrap', function() {
		var pickerPlaceholder = $(this).find('.check-placeholder');
		var optionsObj = $(this).find('option');
		var picker = pickerLoad();
		var options = [];
		optionsObj.each(function() {
			options.push({
				value: $(this).val(),
				text: $(this).text(),
				obj: $(this)
			});
		});

		// 默认选中项
		picker.pickers[0].setSelectedValue(optionsObj.parent().val(), 2000);

		// 选择
		picker.setData(options);
		picker.show(function(selectItems) {
			var uiText = pickerPlaceholder.prev('.checked-item');
			if (uiText.length === 0) {
				uiText = $('<span class="checked-item" data-value="' + selectItems[0].value + '"></span>');
				pickerPlaceholder.before(uiText);
			}
			// 选中显示
			uiText.text(selectItems[0].text);

			if (selectItems[0].value === '') {
				uiText.remove();
			}

			optionsObj.prop('selected', false);
			selectItems[0].obj.prop('selected', true);
		});
	});

	$('body').on('tap', '.sctouch-bottom-mask-close', function() {
		$('.sctouch-bottom-mask').removeClass('up');
	});

	// 微信快捷登录
	$('.joint-login .btn-wechat').on('tap', function() {
		// 显示加载中
		window.layerIndex = layer.open({
			type: 2,
			shadeClose: false
		});
		wxLoginFn(function(wxUserInfo) {
			layer.close(layerIndex);
			baseApi.post('connect/app_login', {
				unionid: wxUserInfo.unionid || wxUserInfo.openid
			}, function(result) {
				if (result.key) {
					updateCookieCart(result.key);
					addCookie("username", result.username);
					addCookie("key", result.key);
					// 登录成功后回调
					loginSuccessCallback();
				} else {
					var layerIndex = layer.open({
						shadeClose: false,
						content: '微信账号尚未绑定，前往注册',
						btn: ['确定', '取消'],
						yes: function(index) {
							layer.close(layerIndex);
							localCache('reg_wxinfo', wxUserInfo);
							pageChange($('.register-url').data('url'));
						}
					});
				}
			});
		})
	});

	// 关闭弹出层
	$('body').on('tap', '.layui-layer-close', function() {
		layer.closeAll();
	});

	// 节点复制
	$('body').on('tap', '.copy-to-clip', function() {
		var target = $(this).data('target');
		var notice = $(this).data('notice');
		var callback = $(this).data('callback');
		copyToClip($(target).text(), notice, callback);
	});
	
	// 分享二维码
	$("body").on('tap', '.order-qrcode',function() {
	    var url = $(this).data('url');
	    layer.open({
	        content: '<img src="' + url + '">'
	        , btn: ['关闭']
	        , yes: function (index) {
	            // copyOrderNO();
	            layer.close(index);
	        }
	    });
	});
	
	// 页面跳转
	$('body').on('tap', '.open-url', function() {
		var url = $(this).data('url');
		var data = $(this).data();
		var params = JSON.parse(JSON.stringify(data || {}));

		delete params.url;

		// 缓存
		params._random = Math.random();

		pageChange(url, params);

		return false;
	});

	// 页面跳转
	$('body').on('tap', '.ex-open-url', function() {
		var url = $(this).data('url');
		var data = $(this).data();
		var params = JSON.parse(JSON.stringify(data || {}));

		delete params.url;
		delete params.href;

		// 缓存
		params._random = Math.random();

		if (isPlusReady()) {
			getOpennerWindow().evalJS('pageChange("' + url + '", ' + JSON.stringify(params) + ')');
			closeCurrentWindow();
		} else {
			pageChange(url, params);
		}
		return false;
	});

	// 认购
	var currentGoodsInfo = null;
	$('body').on('tap', '.goods-subscribe', function() {

		var goods_id = $(this).data('goods_id');
		if (!checkLoginStatus()) return;

		//判断是否可以认购
		baseApi.get('membersubscribe/is_subscribe', {}, function(result) {
			if (result && result.inviter_state == 1) {
				// 获取产品认购详情
				baseApi.get('goods/goods_detail', {
					goods_id: goods_id
				}, function(result) {
					currentGoodsInfo = result.goods_detail.goods_info;
					if (currentGoodsInfo.time_goods.state == 3) {
						mui.toast('商品已售罄');
						return;
					}
					goodsSubscribeLayerShow(result.goods_detail);
				});
			} else {
				mui.toast('账号尚未激活，无法认购');
			}
		});

	});

	// 销售价格修改或认购添加
	$('body').on('tap', '.goods-subscribe-save', function() {
		if (!checkLoginStatus()) return;
		var custom_price = $('#product_subscribe_html .custom-price').val().toFloat();
		var price = $('#product_subscribe_html .price').text().toFloat();
		var profit_price = $('#product_subscribe_html .goods-profit .price-value').text();
		var goods_price_grade = $('#product_subscribe_html .price-grade.active').data('value');
		if (!price) {
			mui.toast('请填写销售价');
			return;
		}
		baseApi.post("/membersubscribe/save.html", {
			goods_id: currentGoodsInfo.goods_id,
			time_goods_id: currentGoodsInfo.time_goods.time_goods_id,
			price: custom_price
		}, function(result) {
			mui.toast(result);
			var goodsSubscribe = $('.goods-subscribe[data-goods_id="' + currentGoodsInfo.goods_id + '"]');
			goodsSubscribe.addClass('favorate').show();
			goodsSubscribe.find('.custom-price').text(custom_price.number_format(2));
			if (goodsSubscribe.find('.custom-price-profit').length > 0) {
				goodsSubscribe.find('.custom-price-profit').text(profit_price);
			}
			if (goodsSubscribe.find('.custom-price-label').length > 0) {
				goodsSubscribe.find('.custom-price-label').text('销售价');
			}
			goodsSubscribe.find('.desc').text('已认购');
			$('.site-subscribe[data-goods_id="' + currentGoodsInfo.goods_id + '"]').hide();
			goodsSubscribeLayerShow(false);
			window.goods_subscribe = true;
		}, function(result) {});
	});

	$('body').on('focus', '#product_subscribe_html .custom-price', function() {
		var val = $(this).val();
		if(val == window.defaultCustomPrice) {
			$(this).val('');
			window.defaultCustomPrice = 0;
		}
	});
	//价格力
	$('body').on('input change', '#product_subscribe_html .custom-price', function() {
		var custom_price = $('#product_subscribe_html .custom-price').val();
		var price = parseFloat($('#product_subscribe_html .price').text());
		var market_price = parseFloat($('#product_subscribe_html .market-price .price-value').text());
		var goods_price_grade = custom_price / market_price * 100;

		var goodsSubscribeLayer = $('#product_subscribe_html');

		goodsSubscribeLayer.find('.price-calc .goods-profit .price-value').text('??');

		window.goods_price_grade_calc = window.goods_price_grade_calc || 0;
		window.goods_price_grade_calc++;
		baseApi.post("/membersubscribe/goods_price_grade.html", {
			goods_price_grade: goods_price_grade,
			n: goods_price_grade_calc,
			time_goods_id: window.popupSubscribeGoodsDetail.goods_info.time_goods.time_goods_id,
			custom_price: custom_price
		}, function(result) {
			if (window.goods_price_grade_calc != result.n) return;

			if (result.grade === '异常' && custom_price >= price) {
				result.grade = '很强↑↑';
			}
			if (custom_price > market_price * 2) {
				result.grade = '异常';
			}

			//  赚多少
			goodsSubscribeLayer.find('.price-calc .goods-profit .price-value').text(custom_price ? result.profit.number_format(2) : '??');
			if(result.tax_rate > 0) {
				goodsSubscribeLayer.find('.bbc-notice').removeClass('mui-hidden');
				goodsSubscribeLayer.find('.tax-rate').text(result.tax_rate.number_format(2) + '%');
			} else {
				goodsSubscribeLayer.find('.bbc-notice').addClass('mui-hidden');
			}

			$('#product_subscribe_html .price-grade[data-value="' + result.grade + '"]').addClass('active').siblings().removeClass('active');
		}, function(result) {
			// 失败回调
			goodsSubscribeLayerShow(false); // 隐藏弹出层
		});
	})

	$('body').on('tap', '#product_subscribe_html .sctouch-bottom-mask-close', function() {
		goodsSubscribeLayerShow(false);
	});

	// 提醒我
	$('body').on('tap', '.goods-prompt-add', function() {
		var goods_id = $(this).data('goods_id');
		var time_goods_id = $(this).data('time_goods_id');
		var type = $(this).data('type');
		var thisObj = $(this);
		baseApi.post("/goods/arrival_notice_add.html", {
			goods_id: goods_id,
			time_goods_id: time_goods_id,
			type: type
		}, function(result) {
			mui.toast(result);
			if (thisObj.data('callback') === 'reload') {
				location.reload();
			} else {
				thisObj.text('取消提醒');
			}
		}, 'json');

	});

	// 添加购物车
	$('body').on('tap', '.goods-list .add-to-cart', function() {
		var goods_id = $(this).data('goods_id');
		var time_goods_id = $(this).data('time_goods_id');
		var goodsImgObj = $(this).parents('.item').find('.goods_image img');
		addToCart(goods_id, time_goods_id, function() {
			var flyEndObj = $("#foot_nav_cart");
			if (flyEndObj.length === 0) {
				flyEndObj = $('#head_nav_cart');
			}

			if (flyEndObj.length === 0) {
				return;
			}

			var e = goodsImgObj.clone().css({
				"z-index": "9999",
				"position": "absolute",
				height: "3rem",
				width: "3rem",
				left: 0,
				"border-radius": '1.5rem',
				"box-shadow": '1px 1px 5px rgba(0, 0, 0, 0.3)',
			});

			if (!e.fly) return;
			e.fly({
				start: {
					left: goodsImgObj.offset().left,
					top: goodsImgObj.offset().top - $(window).scrollTop()
				},
				end: {
					left: flyEndObj.offset().left,
					top: flyEndObj.offset().top - $(window).scrollTop(),
					width: 0,
					height: 0
				},
				onEnd: function() {
					e.remove()
				}
			});
		});
	});

	if (WeiXinOauth) {
		wechatAutoLoginCheck();
	}

	// 获取焦点时
	$(document).on('focus', '.input-num, .input-float', function() {
		var val = $(this).val().toFloat();
		if (val === 0) $(this).val('');
	});

	// 输入格式（整数）
	$(document).on('input', '.input-num', function() {
		var val = $(this).val();
		var max = $(this).data('max');
		var min = $(this).data('min');
		if (val === '') return;
		val = val.toInt();

		if (max != null && val > max) {
			val = max;
		}
		$(this).val(val);
	});
	// 输入格式（小数）
	$('body').on('input', '.input-float', function() {
		var max = $(this).data('max');
		var min = $(this).data('min');
		var digit = $(this).data('digit') || '';

		var val = $(this).val();

		if (val === '') return;

		var format_val = val.toFloat();
		if (!(/^\d+\.\d+$/.test(val))) {
			var endword = val[val.length - 1];
			val = val.toFloat();
			val += (endword == '.' ? '.' : '');
		} else if (digit !== null) { // 有效数位
			val = val.replace(new RegExp('(\\..{' + digit + '}).*$'), '$1');
		}

		if (max !== '' && format_val > max) {
			val = max;
		}
		if (min !== '' && format_val < min) {
			val = min;
		}

		$(this).val(val);
	});

	// 图片下载
	$('body').on('click', '.download-image', function() {
		var imageList = [$(this).data('url')];
		var downloadTasks = [];
		window.downloadSuccess = 0;

		plus.nativeUI.showWaiting();
		imageList.forEach(function(item) {
			downloadTasks.push(new Promise(function(resolve, reject) {
				plus.downloader.createDownload(item, {}, function(d, status) {
					if (status == 200) {
						plus.gallery.save(d.filename, function() { //保存到相册
							window.downloadSuccess++;
							resolve(1);
						})
					} else {
						resolve(0);
					}
				}).start();
			}))
		});
		// 下载任务捕获
		Promise.all(downloadTasks).then(function(result) {
			plus.nativeUI.closeWaiting();
			mui.toast('保存成功');
		});
	});

	// 查看图片
	$('body').on('tap', '.photo-gallery-container', function() {
		let imgContainer = $(this).parent('.video-img');
		let index = imgContainer.find('img').index($(this));
		if (typeof PhotoSwipe === 'undefined') {
			loadPhotoSwipe().then(function() {
				photoSwipePopup(imgContainer.find('img'), index);
			});
		} else {
			photoSwipePopup(imgContainer.find('img'), index);
		}
	});
}());
